package org.example.likou150.array;

/*
* https://leetcode.cn/problems/majority-element/?envType=study-plan-v2&envId=top-interview-150
* */

public class MajorityElement {

    public static void main(String[] args) {
        int[] nums = new int[]{2,2,1,1,1,2,2};
        MajorityElement majorityElement=new MajorityElement();
        System.out.println(majorityElement.majorityElement(nums));
    }

    public int majorityElement(int[] nums) {
        int e = nums[0];
        int count = 0;
        for (int i = 1; i < nums.length; i++) {
            if (e == nums[i]) {
                count++;
            } else if (--count < 0){
                e = nums[i+1];
            }
        }
        return e;
    }

//    public int majorityElement(int[] nums) {
//        Arrays.sort(nums);
//        return nums[nums.length/2];
//    }
}
